package com.ysd.lis.service.samsto.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.toolkit.MPJWrappers;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.lis.dto.samsto.SamstoFridgeDto;
import com.ysd.lis.entity.SysOrgDepartment;
import com.ysd.lis.entity.SysUser;
import com.ysd.lis.entity.eq.EqPatrolTaskEq;
import com.ysd.lis.entity.eq.EqPatrolTaskEqSt;
import com.ysd.lis.entity.samsto.SamstoFridgeLayer;
import com.ysd.lis.entity.samsto.SamstoFridgeModel;
import com.ysd.lis.entity.samsto.SamstoStorageFridge;
import com.ysd.lis.mapper.samsto.SamstoFridgeMapper;
import com.ysd.lis.entity.samsto.SamstoFridge;
import com.ysd.lis.request.samsto.SamstoFridgeParam;
import com.ysd.lis.service.samsto.SamstoFridgeService;
import com.ysd.util.RedisUserManager;
import com.ysd.util.ToolsUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 冰箱表(SamstoFridge)表服务实现类
 *
 * @author leiming
 * @since 2024-10-24 17:14:59
 */
@Service("samstoFridgeService")
public class SamstoFridgeServiceImpl extends ServiceImpl<SamstoFridgeMapper, SamstoFridge> implements SamstoFridgeService {

    private MPJLambdaWrapper<SamstoFridge> initWrapper(){
        MPJLambdaWrapper<SamstoFridge> queryWrapper = MPJWrappers.lambdaJoin(SamstoFridge.class);;
        //ID
        queryWrapper.selectAs(SamstoFridge::getId, SamstoFridgeDto::getId);
        //编号
        queryWrapper.selectAs(SamstoFridge::getBoxCode, SamstoFridgeDto::getBoxCode);
        //条码号
        queryWrapper.selectAs(SamstoFridge::getBoxBarcode, SamstoFridgeDto::getBoxBarcode);
        //冰箱型号
        queryWrapper.selectAs(SamstoFridge::getFrimodId, SamstoFridgeDto::getFrimodId);
        //仓库
        queryWrapper.selectAs(SamstoFridge::getStorageId, SamstoFridgeDto::getStorageId);
        //架层
        queryWrapper.selectAs(SamstoFridge::getLayerNum, SamstoFridgeDto::getLayerNum);
        //冷藏温度
        queryWrapper.selectAs(SamstoFridge::getFrigTemp, SamstoFridgeDto::getFrigTemp);
        //冷冻温度
        queryWrapper.selectAs(SamstoFridge::getFreezeTemp, SamstoFridgeDto::getFreezeTemp);
        //使用标本盒类型范围
        queryWrapper.selectAs(SamstoFridge::getBoxTypesRange, SamstoFridgeDto::getBoxTypesRange);
        //位置排序
        queryWrapper.selectAs(SamstoFridge::getSeq, SamstoFridgeDto::getSeq);
        //状态
        queryWrapper.selectAs(SamstoFridge::getStatus, SamstoFridgeDto::getStatus);
        //机构
        queryWrapper.selectAs(SamstoFridge::getOrgId, SamstoFridgeDto::getOrgId);
        //所属科室
        queryWrapper.selectAs(SamstoFridge::getDeptName, SamstoFridgeDto::getDeptName);
        //删除标记
        queryWrapper.selectAs(SamstoFridge::getDelFlag, SamstoFridgeDto::getDelFlag);
        //创建人
        queryWrapper.selectAs(SamstoFridge::getCreator, SamstoFridgeDto::getCreator);
        //创建时间
        queryWrapper.selectAs(SamstoFridge::getCreateTime, SamstoFridgeDto::getCreateTime);
        //修改人
        queryWrapper.selectAs(SamstoFridge::getEditor, SamstoFridgeDto::getEditor);
        //修改时间
        queryWrapper.selectAs(SamstoFridge::getEditTime, SamstoFridgeDto::getEditTime);
        //删除时间
        queryWrapper.selectAs(SamstoFridge::getDelTime, SamstoFridgeDto::getDelTime);
        return queryWrapper;
    }

    @Override
    public Result findPageList(SamstoFridgeParam pageParam) {
        return  this.findListByGId(pageParam);//fixme:暂时无用需要优化
    }

    @Override
    public Result getAllList(SamstoFridgeParam pageParam) {
        MPJLambdaWrapper<SamstoFridge>  queryWrapper=initWrapper();
        queryWrapper.selectAs(SysOrgDepartment::getName,SamstoFridgeDto::getDeptNameer);
        queryWrapper.selectAs(SamstoFridgeModel::getModelName,SamstoFridgeDto::getModelName);
        queryWrapper.leftJoin(SysOrgDepartment.class,SysOrgDepartment::getCode,SamstoFridge::getDeptName);
        queryWrapper.leftJoin(SamstoFridgeModel.class,SamstoFridgeModel::getId,SamstoFridge::getFrimodId);
        List<SamstoFridgeDto> samstoFridgeDtos=new ArrayList<>();
        if(StringUtils.isNotBlank(pageParam.getFrimodId())){
            queryWrapper.eq(SamstoFridge::getFrimodId, pageParam.getFrimodId());
        }
        queryWrapper.eq(SamstoFridge::getDelFlag, 0);
        if (StringUtils.isNotBlank(pageParam.getKeywords())) {
            queryWrapper.and(wrapper -> wrapper.like(SamstoFridge::getBoxBarcode, pageParam.getKeywords())
                    .or().like(SamstoFridge::getBoxCode, pageParam.getKeywords()));
        }
        queryWrapper.orderByAsc(SamstoFridge::getCreateTime);
        try{
            SysUser sysUser = RedisUserManager.getUser();
            if (ToolsUtils.isNotEmpty(sysUser)) {
                queryWrapper.eq(SamstoFridge::getOrgId, sysUser.getOrgId());
            }
            samstoFridgeDtos= this.baseMapper.selectJoinList(SamstoFridgeDto.class,queryWrapper);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return Result.succ(1, "获取信息成功", samstoFridgeDtos);
    }

    @Override
    public Result getAllFridgeList(SamstoFridgeParam pageParam) {
        MPJLambdaWrapper<SamstoFridge>  queryWrapper=new MPJLambdaWrapper<>();
        queryWrapper.distinct();
        queryWrapper.selectAll(SamstoFridge.class);
        queryWrapper.selectCollection(SamstoFridgeLayer.class,SamstoFridge::getLayerList);
        queryWrapper.leftJoin(SamstoFridgeLayer.class, SamstoFridgeLayer::getFridgeId, SamstoFridge::getId);
        queryWrapper.eq(SamstoFridge::getDelFlag,0);
        List<SamstoFridge> samstoFridges = this.baseMapper.selectJoinList(SamstoFridge.class, queryWrapper);
        return Result.succ(1, "查询成功！", samstoFridges);
    }

    @Override
    public Result getAllListNotLink(SamstoFridgeParam pageParam) {
        MPJLambdaWrapper<SamstoFridge>  queryWrapper=initWrapper();
        queryWrapper.selectAs(SysOrgDepartment::getName,SamstoFridgeDto::getDeptNameer);
        queryWrapper.selectAs(SamstoFridgeModel::getModelName,SamstoFridgeDto::getModelName);
        queryWrapper.leftJoin(SysOrgDepartment.class,SysOrgDepartment::getCode,SamstoFridge::getDeptName);
        queryWrapper.leftJoin(SamstoFridgeModel.class,SamstoFridgeModel::getId,SamstoFridge::getFrimodId);
        queryWrapper.leftJoin(SamstoStorageFridge.class,SamstoStorageFridge::getFridgeId,SamstoFridge::getId);
        queryWrapper.leftJoin(SamstoStorageFridge.class,item-> item.eq(SamstoStorageFridge::getFridgeId,SamstoFridge::getId).eq(SamstoStorageFridge::getDelFlag,0));
        //queryWrapper.ne(SamstoStorageFridge::getStorageId,pageParam.getStorageId());
        queryWrapper.isNull(SamstoStorageFridge::getFridgeId);
        List<SamstoFridgeDto> samstoFridgeDtos=new ArrayList<>();
        if(StringUtils.isNotBlank(pageParam.getFrimodId())){
            queryWrapper.eq(SamstoFridge::getFrimodId, pageParam.getFrimodId());
        }
        queryWrapper.eq(SamstoFridge::getDelFlag, 0);
        if (StringUtils.isNotBlank(pageParam.getKeywords())) {
            queryWrapper.and(wrapper -> wrapper.like(SamstoFridge::getBoxBarcode, pageParam.getKeywords())
                    .or().like(SamstoFridge::getBoxCode, pageParam.getKeywords()));
        }
        queryWrapper.orderByAsc(SamstoFridge::getCreateTime);
        try{
            SysUser sysUser = RedisUserManager.getUser();
            if (ToolsUtils.isNotEmpty(sysUser)) {
                queryWrapper.eq(SamstoFridge::getOrgId, sysUser.getOrgId());
            }
            samstoFridgeDtos= this.baseMapper.selectJoinList(SamstoFridgeDto.class,queryWrapper);
        }catch (Exception e) {
            e.printStackTrace();
        }
        ArrayList<SamstoFridgeDto> collect = samstoFridgeDtos.stream().collect(Collectors.collectingAndThen(Collectors.toMap(SamstoFridgeDto::getBoxCode, dto -> dto, (existing, replacement) -> existing), map -> new ArrayList<>(map.values())));
        return Result.succ(1, "获取信息成功", collect);
    }

    @Override
    public Result findListByGId(SamstoFridgeParam pageParam) {
        MPJLambdaWrapper<SamstoFridge>  queryWrapper=initWrapper();
        queryWrapper.selectAs(SysOrgDepartment::getName,SamstoFridgeDto::getDeptNameer);
        queryWrapper.selectAs(SamstoFridgeModel::getModelName,SamstoFridgeDto::getModelName);
        queryWrapper.leftJoin(SysOrgDepartment.class,SysOrgDepartment::getCode,SamstoFridge::getDeptName);
        queryWrapper.leftJoin(SamstoFridgeModel.class,SamstoFridgeModel::getId,SamstoFridge::getFrimodId);
        Page<SamstoFridgeDto> page = new Page<SamstoFridgeDto>();
        page.setCurrent(pageParam.getPageIndex());
        page.setSize(pageParam.getPageSize());
        if(StringUtils.isNotBlank(pageParam.getFrimodId())){
            queryWrapper.eq(SamstoFridge::getFrimodId, pageParam.getFrimodId());
        }
        queryWrapper.eq(SamstoFridge::getDelFlag, 0);
       if (StringUtils.isNotBlank(pageParam.getKeywords())) {
           queryWrapper.and(wrapper -> wrapper.like(SamstoFridge::getBoxBarcode, pageParam.getKeywords())
                    .or().like(SamstoFridge::getBoxCode, pageParam.getKeywords()));
        }
        queryWrapper.orderByAsc(SamstoFridge::getCreateTime);
        try{
            SysUser sysUser = RedisUserManager.getUser();
            if (ToolsUtils.isNotEmpty(sysUser)) {
                queryWrapper.eq(SamstoFridge::getOrgId, sysUser.getOrgId());
            }
            page= this.baseMapper.selectJoinPage(page,SamstoFridgeDto.class,queryWrapper);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return Result.succ(1, "获取信息成功", page);
    }

    @Override
    public Result getInfoById(String id) {
        SamstoFridge SamstoFridge=this.baseMapper.selectById(id);
        return Result.succ(1, "获取信息成功", SamstoFridge);
    }

    @Override
    public Result add(SamstoFridgeParam param) {
        SamstoFridge info=new SamstoFridge();
        try{
            SysUser sysUser = RedisUserManager.getUser();
            if (ToolsUtils.isNotEmpty(sysUser)) {
                param.setCreator(sysUser.getId());
                param.setOrgId(sysUser.getOrgId());
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        param.setCreateTime(new Date());
        BeanUtil.copyProperties(param,info);
        info.setDelFlag(0);
        info.setStatus(1);
        this.baseMapper.insert(info);
        return Result.succ(1, "添加信息成功", null);
    }

    @Override
    public Result edit(SamstoFridgeParam param) {
        Map returnMap = new HashMap();
        SamstoFridge info=new SamstoFridge();
        try{
            SysUser sysUser = RedisUserManager.getUser();
            if (ToolsUtils.isNotEmpty(sysUser)) {
                param.setEditor(sysUser.getId());
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        param.setEditTime(new Date());
        BeanUtil.copyProperties(param,info);
        this.baseMapper.updateById(info);
        returnMap.put("id", param.getId());
        return Result.succ(1, "修改信息成功", returnMap);
    }

    @Override
    public Result delete(List<String> ids) {
        Result result;
        try {
            boolean b = this.removeByIds(ids);
            if (b) {
                result = Result.succ(1, "删除成功", null);
            } else {
                result = Result.fail(400, "删除失败", "");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.fail(400, "删除失败", "");
        }
        return result;
    }

    @Override
    public Result updelete(List<String> ids) {
        Result result;
        LambdaUpdateWrapper<SamstoFridge> lambdaUpdateWrapper = new UpdateWrapper<SamstoFridge>().lambda();
        // set 表示要更新的字段， eq 表示  WHERE 条件
        lambdaUpdateWrapper.set(SamstoFridge::getDelFlag,1)
                .in(SamstoFridge::getId, ids);
        this.baseMapper.update(new SamstoFridge(), lambdaUpdateWrapper);

        try {
            int b= this.baseMapper.update(new SamstoFridge(), lambdaUpdateWrapper);
            if (b>0) {
                result = Result.succ(1, "删除成功", null);
            } else {
                result = Result.fail(400, "删除失败", "");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.fail(400, "删除失败", "");
        }
        return result;
    }

    @Transactional
    @Override
    public Result saveOrUpdateList(SamstoFridgeParam param) {
        Result result;
        try {
            SysUser sysUser = RedisUserManager.getUser();
            if (ToolsUtils.isEmpty(sysUser)) {
               return Result.fail(304, "请重新登陆", "");
            }
            for (SamstoFridge info : param.getInfoList()) {
                if(StringUtils.isNotBlank(info.getId())){
                    info.setEditor(sysUser.getId());
                    info.setEditTime(new Date());
                    this.baseMapper.updateById(info);
                }else{
                    info.setCreator(sysUser.getId());
                    info.setOrgId(sysUser.getOrgId());
                    info.setCreateTime(new Date());
                    info.setDelFlag(0);
                    info.setStatus(1);
                    this.baseMapper.insert(info);
                }
            }
            Boolean b= this.saveOrUpdateBatch(param.getInfoList());
            if (b) {
                result = Result.succ(1, "保存成功", null);
            } else {
                result = Result.fail(400, "保存失败", "");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.fail(400, "保存失败", "");
        }
        return result;
    }
}

